package com.cicc.beergamevirtualsimulationsystem.common.webSocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {



        String path = request.getURI().getPath();

        //log.info("ws请求路径: {}", path);
        Pattern pattern = Pattern.compile("/link/(\\d+)/(\\d+)");
        Matcher matcher = pattern.matcher(path);

        if (matcher.find()) {
            String userId = matcher.group(1);
            String roomId = matcher.group(2);
            attributes.put("userId", userId);
            attributes.put("roomId", roomId);
            //log.info("userId: {}, roomId: {}", userId, roomId);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {

    }
}


